import datetime
import random
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render,redirect,reverse

from app1.models import Order, Emp
from app1.util.pagination import Pagination


def order_list(request):
    queryset = Order.objects.all()
    page = Pagination(request,queryset)
    emp_list = Emp.objects.all()[0:10]
    return render(request,'order/order_list.html',{'emp_list':emp_list,'order_list':page.get_page_result(),'page_str':page.get_page_str()})


def order_add(request):
    #items = request.GET.items()

    title = request.GET.get('title','')
    price = request.GET.get('price','')
    status = request.GET.get('status','')
    empno = request.GET.get('empno','')
    resp_dict = {'status':True,'errors': {}}
    if title=='':
        resp_dict['errors']['title'] = '名称不能为空！'
    if price == '':
        resp_dict['errors']['price'] = '价格不能为空！'
    if status=='':
        resp_dict['errors']['status'] = '状态不能为空！'
    if empno=='':
        resp_dict['errors']['empno'] = '用户不能为空！'
    if resp_dict['errors']:
        resp_dict['status'] = False


    if resp_dict['status']:
        orderid = datetime.datetime.now().strftime('%Y%m%d%H%M%S')+str(random.randint(10000,99999))
        Order.objects.create(orderid=orderid,title=title,price=price,status=status,emp_id=empno)


    return JsonResponse(resp_dict,content_type='application/json')


# 下面的修改和刪除是新增的request


def order_update(request):
    if request.method=='GET':
        id = request.GET.get('id')
        order = Order.objects.filter(id=id).first()

        emp_list = Emp.objects.all()[0:10]
        return render(request,'order/order_update.html',{'order':order,'emp_list':emp_list})
    id = request.POST.get('id')
    title = request.POST.get('title', '')
    price = request.POST.get('price', '')
    status = request.POST.get('status', '')
    empno = request.POST.get('empno', '')
    Order.objects.filter(id=id).update(title=title,price=price,status=status,emp_id=empno)
    return redirect(reverse('order_list'))

def order_delete(request):
    id = request.GET.get('id')
    Order.objects.filter(id=id).delete()
    return redirect(reverse('order_list'))